<script setup>
import {onMounted, ref} from 'vue';
import {useRoute} from 'vue-router';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {router} from "@/router/index.js";
import {userStore} from '@/store/index.js'

const userItemStore = userStore();

const route = useRoute();
const productId = route.params.id;

const activeTab = ref('overview'); // 新增: 初始化 activeTab 用于切换标签页

const car = ref(null);
const getCarById = async () => {
  try {
    const response = await axios.get(`/car/getCarById`, { params: { id: productId } });
    car.value = response.data;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const calculateDailyPayment = (price) => {
  const interestRate = 0.05;
  const days = 3650;
  const dailyRate = interestRate / 365; // 日利率
  const dailyPayment = (price * dailyRate) / (1 - Math.pow(1 + dailyRate, -days));
  return dailyPayment > 0 ? dailyPayment.toFixed(0) : '0.00';
};

const reviews = ref([]);
const getCarReviews = async () => {
  try {
    const reviewResponse = await axios.get('/reviews/getReviewsByCarId', { params: { carId: productId } });
    reviews.value = reviewResponse.data;
    const userPromises = reviews.value.map(async (review) => {
      review.username = await getReviewsByUserId(review.userId);
    });
    await Promise.all(userPromises);

  } catch (error) {
    ElMessage.error(error.message);
  }
};

const users = ref({});
const getReviewsByUserId = async (userId) => {
  try {
    const response = await axios.get('/reviews/getReviewsByUserId', {
      params: { userId: userId }
    });
    return response.data[0]?.username || '未知用户'; // 防止没有数据时返回默认值
  } catch (error) {
    console.error(error.message);
    return '未知用户'; // 如果获取失败，返回默认用户名
  }
};

const checkLoginAndNavigate=(routeName, productId)=> {
  if (userItemStore.loggedIn) {
    router.push({ name: routeName, params: { id: productId } });
  } else {
    router.push({ name: 'login' });
    ElMessage.warning('请先登录')
  }
}

const calculateMonthlyPayment = (price) => {
  const interestRate = 0.05;
  const months = 120;
  const monthlyRate = interestRate / 12;
  const monthlyPayment = (price * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months));
  return monthlyPayment > 0 ? monthlyPayment.toFixed(2) : '0.00';
};


onMounted(() => {
  getCarById();
  getCarReviews();
});
</script>

<template>
  <div>
    <div v-if="car" class="car-details" :style="{ backgroundImage: 'url(' + $urlImage + car.imgs + ')' }">
      <div class="content">
        <h3>{{ car.name }}</h3>
        <p>“日付”低至{{ calculateDailyPayment(car.price) }}元</p>
        <el-button class="full-width-button" @click="checkLoginAndNavigate('reservation', productId)">预约试驾</el-button>
      </div>

    </div>
  </div>
  <!-- 标签页部分 -->
  <div class="tabs" v-if="car">
    <p>{{ car.name }} <span class="separator">|</span></p>
    <div
        class="tab-item"
        :class="{'active-tab': activeTab === 'overview'}"
        @click="activeTab = 'overview'">概述</div>
    <div
        class="tab-item"
        :class="{'active-tab': activeTab === 'details'}"
        @click="activeTab = 'details'">详情</div>

    <div
        class="tab-item"
        :class="{'active-tab': activeTab === 'specs'}"
        @click="activeTab = 'specs'">此车评论</div>

    <div
        class="tab-item"
        :class="{'active-tab': activeTab === 'tips'}"
        @click="checkLoginAndNavigate('configure', productId)">配置爱车</div>


  </div>


  <div v-if="activeTab === 'overview'" class="tab-content">
    <h1>本色，当先</h1>
    <div class="image-container">
      <div class="image-item-wrapper">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/highlight_430702790/highlightitems/highlightitem_aa48/image.transform/highlight/image.1724842509015.jpg" alt="Image 1" class="image-item" />
        <div class="image-overlay">
          <h1>01</h1>
          <p>运动外观型格</p>
        </div>
      </div>
      <div class="image-item-wrapper">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/highlight_430702790/highlightitems/highlightitem_992d/image.transform/highlight/image.1724902488828.jpg" alt="Image 2" class="image-item" />
        <div class="image-overlay">
          <h1>02</h1>
          <p>考究内饰空间</p>
        </div>
      </div>
      <div class="image-item-wrapper">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/highlight_430702790/highlightitems/highlightitem_c17e/image.transform/highlight/image.1724842544286.jpg" alt="Image 3" class="image-item" />
        <div class="image-overlay">
          <h1>03</h1>
          <p>恣意驾驶乐趣</p>
        </div>
      </div>
      <div class="image-item-wrapper">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/highlight_430702790/highlightitems/highlightitem_9d43/image.transform/highlight/image.1724842572781.jpg" alt="Image 4" class="image-item" />
        <div class="image-overlay">
          <h1>04</h1>
          <p>智享前瞻科技</p>
        </div>
      </div>
    </div>

    <div class="text-image-container" v-if="car">
      <div class="text-content">
        <h1>凌厉姿态，由内而外</h1>
        <p>不刻意标新立异，却自然与众不同。{{car.name}}运用实用又迷人的美学设计，为车身内外都注入了轩昂充沛的个性。LED大灯用光亮划破夜幕，让驾驶者随时都能拥有理想的可视度，可自如舒展的座椅与智能感应光脉饰条则营造了优雅又舒适的仪式感。</p>
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/mosaicgallery_2017204533/items/mosaicgalleryitem_a3/image.transform/mosaic485/image.1724842649089.jpg" class="image-item" alt="Image 6"/>
      </div>
      <div class="image-content">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/2-series/coupe/2021/inspire/jcr:content/par/mosaicgallery_2017204533/items/mosaicgalleryitem_1b/image.transform/mosaic963/image.1724842699907.jpg" class="image-item" alt="Image 5"/>
      </div>
    </div>

    <div class="text-image-container" v-if="car">
      <div class="text-content">
        <h1>锐意张扬，天性难挡</h1>
        <p>{{car.name}}澎湃内蕴，自然流露为驾驶而生的罕见锋芒。高效动力提供出众的驾驶乐趣，也带来出众的运动风格和卓越的驾驶性能表现。以精准独到的操控体验，令动魄气场尽在掌控。</p>
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/4-series/coupe/2024/inspire/jcr:content/par/mosaicgallery1/items/mosaicgalleryitem_391510334/image.transform/mosaic963/image.1713771272159.jpg" class="image-item" alt="Image 7"/>
        <h1>所见，大美至简</h1>
        <p>一经登场，尽释主角光芒。{{car.name}}魅力外展，优雅独到的雕塑感外观设计勾勒从容姿态，标志性的流线型车身线条，动静之间，弘美之感跃然呈现。</p>
      </div>
      <div class="image-content">
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/4-series/coupe/2024/inspire/jcr:content/par/mosaicgallery1/items/mosaicgalleryitem_3915103341/image.transform/mosaic485/image.1713771330708.jpg" class="image-item" alt="Image 8"/>
        <img src="https://www.bmw.com.cn/content/bmw/marketCN/bmw_com_cn/zh_CN/all-models/4-series/convertible/2024/inspire/jcr:content/par/mosaicgallery/items/mosaicgalleryitem_40009326/image.transform/mosaic485/image.1713774126529.jpg" class="image-item" alt="Image 9"/>
      </div>
    </div>

  </div>

  <div v-if="activeTab === 'details'" class="car-details">
    <div v-if="car">
      <h1>{{ car.name }}
        <el-popover
            placement="top-start"
            :width="300"
            trigger="hover"
            content="所示价格为建议零售价,产品车型图片仅供参考，相关具体车型及配置请以当地授权经销商店内为准">
          <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
          </template>
        </el-popover></h1>
      <h2>车型售价 ¥{{ car.price }} 起</h2>
      <h2>月付：¥{{ calculateMonthlyPayment(car.price) }}起
        <el-popover
            placement="top-start"
            :width="300"
            trigger="hover"
            content="注:月付是以10年期，年化率5%的月付利息，不包含首付款和保险费用。">
          <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
          </template>
        </el-popover>
      </h2>
      <img :src="$urlImage + car.imgs" alt="车图片"/>
      <div class="divider"></div>

      <h1>0-100公里/小时  {{ car.acceleration }}秒</h1>

      <h1>最高时速  {{ car.maxSpeed }}公里/小时</h1>

      <h1>综合耗油量  {{car.fuelConsumption}}(L/每100公里)</h1>

      <a href="https://www.bmw.com.cn/content/dam/bmw/marketCN/common/all-models/specsheet-pdf/spec/2024/20240828/G42LCI_BMW_2er_0824_web.pdf.asset.1724935199363.pdf"
         target="_blank"
         class="download-btn">
        下载详细配置进行查看
      </a>

    </div>
  </div>


  <div v-if="activeTab === 'specs'" class="tab-content">
    <h2>此车评论</h2>
    <div v-if="reviews.length > 0">
      <div v-for="(review, index) in reviews" :key="index" class="review-box">
        <p class="review-author">
          <strong>{{review.username}}</strong>
          <span class="review-date">{{ review.reviewDate }}</span>
        </p>
        <p class="review-rating">评分: {{ review.rating }}/10</p>
        <p class="review-text">{{ review.reviewText }}</p>
      </div>
    </div>
    <div v-else>
      <p>暂无评论</p>
    </div>
  </div>


  <div class="button-container">
    <div
        class="tab-item"
        style="background-color: #ccc; width: 200px; text-align: center;"
        :class="{'active-tab': activeTab === 'specs'}"
        @click="checkLoginAndNavigate('reservation', productId)">预约试驾</div>

    <div
        class="tab-item"
        style="background-color: #cfb269; width: 200px; text-align: center;"
        :class="{'active-tab': activeTab === 'specs'}"
        @click="checkLoginAndNavigate('ratingForm', productId)">给我们评价</div>

  </div>

  <el-backtop :right="100" :bottom="100" />
</template>

<style scoped>

/* 使下载按钮右对齐，并设置透明蓝色字体 */
.download-btn {
  position: absolute;
  right: 0;
  bottom: 20px; /* 可以根据需要调整距离 */
  background: transparent;
  color: rgba(0, 0, 255, 0.7); /* 蓝色透明 */
  border: none;
  font-size: 16px;
  cursor: pointer;
  text-decoration: underline;
}
/* 详情部分的整体布局 */
.car-details {
  width: 80%;
  margin: 0 auto;  /* 居中显示 */
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  background-color: #fff;
}

.car-details h1, .car-details h2 {
  text-align: center;  /* 标题居中 */
  margin-bottom: 20px;
  color: #333;
}

.car-details img {
  max-width: 300px;  /* 图片自适应宽度 */
  height: auto;  /* 保持宽高比 */
  display: block;
  margin: 0 auto;  /* 图片水平居中 */
}

.car-details .divider {
  border-top: 2px solid black;  /* 黑色分隔线 */
  width: 80%;  /* 分隔线占用80% */
  margin: 20px auto 0;  /* 居中显示 */
}

/* 月供信息提示 */
.car-details h2 {
  font-size: 1.2rem;
  color: #555;
}

.el-popover {
  font-size: 0.9rem;  /* 提示框字体大小 */
  padding: 10px;
}

/* 图片容器 */
.car-details .image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.image-container img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
}

.review-box {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.review-author {
  font-size: 1.2rem;
  color: #333;
}

.review-date {
  font-size: 0.9rem;
  color: #999;
  margin-left: 10px;
}

.review-rating {
  font-size: 1.1rem;
  color: #f39c12;
}

.review-text {
  font-size: 1rem;
  margin-top: 10px;
}

.button-container {
  display: flex;  /* 使用 Flexbox 布局 */
  justify-content: center;  /* 将按钮居中 */
  gap: 20px;  /* 按钮之间的间距 */
}

.text-image-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;  /* 图片和文字之间的间距 */
  margin-bottom: 20px;  /* 为了和下面的图片留点空间 */
}

.text-content {
  width: 40%;  /* 文字部分占 40% */
}
.image-content {
  width: 60%;  /* 图片部分占 60% */
}
/* 图片容器，使用flex布局 */
.image-container {
  display: flex;
  justify-content: space-between;
  gap: 10px;  /* 图片之间的间距 */
}

.image-item-wrapper {
  position: relative;
  width: 24%;  /* 保持图片宽度 */
}

.image-item {
  width: 100%;          /* 每张图片占满父容器 */
  height: 600px;        /* 设置图片高度 */
  transition: transform 0.3s ease;  /* 设置图片的过渡效果 */
}

.image-item:hover {
  transform: scale(1.1);  /* 鼠标悬停时放大图片 */
}

/* 图片上的文字层 */
.image-overlay {
  position: absolute;
  bottom: 10px; /* 在图片底部显示文字 */
  left: 10px;   /* 左侧间距 */
  color: #ffffff;
  background-color: rgba(0, 0, 0, 0.0);  /* 半透明背景 */
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 24px;
  font-weight: bold;
}

/* 标签页部分 */
.tabs {
  display: flex;
  margin-left: 400px;
  margin-top: 20px;
}

.tab-item {
  font-size: 24px;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 80px;
  border-radius: 5px;  /* 可选：为按钮添加圆角 */
}

.tab-item:hover {
  font-size: 28px;
}

.active-tab {
  font-weight: bold;
  color: #409EFF; /* 激活的标签文字颜色 */
}

/* 内容部分 */
.tab-content {
  width: 70%;          /* 设置宽度为 80% */
  padding: 20px;       /* 内边距 */
  border: 1px solid #dcdfe6;  /* 边框 */
  border-radius: 5px;  /* 圆角效果 */
  margin: 20px auto 0;
}
.car-details {
  background-size: cover;  /* 背景图片铺满整个容器 */
  background-position: center center; /* 背景图片居中 */
  height: 600px; /* 设定背景容器的高度 */
  color: white; /* 默认文字颜色 */
  padding: 20px; /* 页面内边距 */
  position: relative;
}

.content {
  position: absolute;
  top: 20px;   /* 放置到左上角 */
  left: 20px;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  color: white; /* 白色字体 */
  padding: 15px;
  border-radius: 5px; /* 圆角效果 */
}

.car-details h3 {
  margin: 0 0 10px;
  font-size: 2rem;
}

.car-details p {
  margin: 10px 0;
  font-size: 1.2rem;
}

.full-width-button {
  background-color: white; /* 白色背景 */
  border: 1px solid #dcdfe6; /* 边框颜色 */
  color: #409EFF; /* 按钮文字颜色 */
  width: 100%; /* 使按钮填满父容器 */
  padding: 10px; /* 调整内边距 */
  box-shadow: none; /* 去掉阴影 */
}
</style>
